from typing import Iterator, Any, Generator, List, Tuple, Union
from django.db import connection
from pydantic import BaseModel

def get_sql(sql_list: Iterator[Any]) -> str:
    """生成完整的sql查询语句
    """
    return " ".join(sql_list)


class RowSql(BaseModel):
    """执行原生的sql语句
    """
    fields: Union[List, Tuple]
    table: str

    def get_sql_fiels_names(self) -> str:
        """生成sql查询语句,用于查询表中的字段名
        """
        return ', '.join((f"{self.table}.{field}" for field in self.fields))

    def execute_sql(self, sql_list:Iterator[Any] , params: tuple = None) -> Generator[dict[Any, Any], None, None]:
        """执行sql语句
        """
        
        with connection.cursor() as cursor:
            cursor.execute(get_sql(sql_list), params)
            return (dict(zip(self.fields, row)) for row in cursor.fetchall())